package com.ews.onlineexchange.test;

import java.util.Date;

import javax.enterprise.inject.Model;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;

import com.ews.onlineexchange.model.Bulletin;
import com.ews.onlineexchange.model.ChooseType;
import com.ews.onlineexchange.model.TradeStatus;
import com.ews.onlineexchange.service.schedule.BulletinOverTimer;

@Model
public class BulletinRepairBean {

	@Inject
	EntityManager entityManager;
	
	@Inject
	BulletinOverTimer timer;
	
	private Date newChooseTime; 
	
	@Transactional
	public void triggerTimer(String bulletinId) {
		if(StringUtils.isBlank(bulletinId)) return ;
	
		Bulletin bulletin = entityManager.find(Bulletin.class, bulletinId);
		bulletin.setTradeStatus(TradeStatus.Opened);
		Date now = new Date();
		if(newChooseTime == null)bulletin.setChooseTime(new Date(now.getTime() + 40*1000));
		else {
			if(newChooseTime.before(new Date())) return ;
			bulletin.setChooseTime(newChooseTime);
		}
		bulletin.setOver(false);
		entityManager.merge(bulletin);
		if (!bulletin.getWayOfChoose().equals(ChooseType.Manual))
			timer.registerNewBulletin(bulletin);		
	}

	public Date getNewChooseTime() {
		return newChooseTime;
	}

	public void setNewChooseTime(Date newChooseTime) {
		this.newChooseTime = newChooseTime;
	}
	
	
}
